using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Avalonia.Controls.Notifications;
using Avalonia.Threading;
using AvaloniaApplication1.IServices;
using AvaloniaApplication1.Models;
using AvaloniaApplication1.Models.DTOModel;
using AvaloniaApplication1.Util;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using SukiUI.Dialogs;
using SukiUI.Toasts;

namespace AvaloniaApplication1.ViewModels.CardViewModel;

public partial class DeviceSettingViewModel : ObservableObject
{
    [ObservableProperty] private string _deviceId;
    [ObservableProperty] private IMqttDeviceManager _deviceManager;


    [ObservableProperty] private bool _isVisible = false;
    [ObservableProperty] private string _tips = string.Empty;


    [ObservableProperty] private string? _deviceName = "未初始化";
    [ObservableProperty] private string? _host = "未初始化";
    [ObservableProperty] private string? _userName = "未初始化";
    [ObservableProperty] private int? _port = 0;
    [ObservableProperty] private bool? _isConnected = false;
    [ObservableProperty] private ObservableCollection<MqttTopicConfig>? _topics = new();  // 主题列表 用于UI显示


    [ObservableProperty] private string _inputTopic = string.Empty;
    [ObservableProperty] private int _inputQos = 0;
    [ObservableProperty] private bool _inputSubscription = false;
    [ObservableProperty] private bool _inputPublish = false;


    public DeviceSettingViewModel(IMqttDeviceManager deviceManager, string deviceId)
    {
        DeviceId = deviceId;
        DeviceManager = deviceManager;


        if (DeviceManager.GetDevice(DeviceId) == null) return;
        DeviceName = DeviceManager.GetDevice(DeviceId)?.Description ?? "Unknown";
        Host = DeviceManager.GetDevice(DeviceId)?.Server;
        UserName = DeviceManager.GetDevice(DeviceId)?.Username;
        Port = DeviceManager.GetDevice(DeviceId)?.Port;
        IsConnected = DeviceManager.IsDeviceConnected(DeviceId);
        // 将列表转换为 ObservableCollection
        var deviceTopics = DeviceManager.GetDevice(DeviceId)?.Topics;
        if (deviceTopics != null)
        {
            Topics = new ObservableCollection<MqttTopicConfig>(deviceTopics);
            // 给每个主题订阅所有现有主题的事件
            foreach (var topic in Topics)
            {
                topic.DeleteRequested += OnTopicDeleteRequested;
            }
        }
    }

    /// <summary>
    /// 主题的删除请求处理
    /// </summary>
    /// <param name="topic"></param>
    private async void OnTopicDeleteRequested(MqttTopicConfig topic)
    {
        try
        {
            // 在后台线程执行异步操作
            bool unsubscribeResult = false;
            if (DeviceManager.GetDevice(DeviceId) != null)
            {
                unsubscribeResult = await DeviceManager.UnsubscribeTopic(DeviceId, topic.Topic);
            }

            // 切换回UI线程更新UI
            await Dispatcher.UIThread.InvokeAsync(() =>
            {
                if (unsubscribeResult)
                {
                    Tips = "删除成功";
                    Topics?.Remove(topic);

                    // 刷新Topics
                    var deviceTopics = DeviceManager.GetDevice(DeviceId)?.Topics;
                    if (deviceTopics != null)
                    {
                        Topics = new ObservableCollection<MqttTopicConfig>(deviceTopics);
                        // 重新给每个主题订阅所有现有主题的事件
                        foreach (var t in Topics)
                        {
                            t.DeleteRequested += OnTopicDeleteRequested;
                        }
                    }

                    AppLogger.Information($"remove select topic {topic.Topic} currentTime: {DateTime.Now}");
                }
                else
                {
                    Tips = "删除失败";
                }

                IsVisible = true;
            });
        }
        catch (Exception ex)
        {
            await Dispatcher.UIThread.InvokeAsync(() =>
            {
                Tips = "删除失败: " + ex.Message;
                IsVisible = true;
            });
            AppLogger.Error(ex, "删除主题时发生错误");
        }
    }

    [RelayCommand]
    public void AddTopicCommand()
    {
        //确保UI线程执行
        Dispatcher.UIThread.InvokeAsync(() =>
        {
            if (InputTopic != string.Empty)
            {
                var topic = new MqttTopicConfig(InputTopic, InputQos, InputSubscription, InputPublish);
                Topics?.Add(topic);//用于UI显示

                //更新MqttDeviceModel
                if (DeviceManager.GetDevice(DeviceId) != null)
                {
                    DeviceManager.GetDevice(DeviceId)?.Topics.Add(topic);//用于添加到设备对象中的topic列表
                    DeviceManager.AddTopic(DeviceId,topic.Topic, topic.Qos, topic.IsSubscription, topic.IsPublish);
                    Tips = "添加成功";
                    IsVisible = true;
                }
                else
                {
                    Tips = "添加失败";
                    IsVisible = true;
                }
            }
        });
    }

    [RelayCommand]
    public void TestDialog()
    {
        Tips = "添加成功";
        IsVisible = true;
    }
}